<template>
  <div>
    <el-form
      ref="selectRef"
      :inline="true"
      :model="selectForm"
      :rules="selectFormRules"
      label-width="100px"
      class="demo-form-inline"
    >
      <el-form-item label="串口">
        <el-select v-model="selectForm.comName" placeholder="选择串口">
          <el-option
            v-for="item in Ports"
            :key="item.pnpId"
            :label="item.path"
            :value="item.path"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="波特率">
        <el-select v-model="selectForm.baudRate" placeholder="选择波特率">
          <el-option v-for="item in Bauds" :key="item" :label="item" :value="item"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <!-- <el-button type="primary" @click="onSubmit">确 定</el-button> -->
      </el-form-item>
    </el-form>
  </div>
  <div v-if="msgBoxShow">
    <el-form
      ref="msgRef"
      :model="msgForm"
      label-width="100px"
      class="demo-form-inline"
      :rules="msgFormRules"
    >
      <el-form-item label="发送消息" prop="msg">
        <el-input
          type="textarea"
          :autosize="{ minRows: 2, maxRows: 4 }"
          placeholder="请输入内容"
          v-model="msgForm.msg"
        >
        </el-input>
      </el-form-item>
      <el-form-item style="text-align:right;">
        <el-button type="primary" @click="onSend">发 送</el-button>
      </el-form-item>
    </el-form>
  </div>
  <view-box :leftContent="leftContent" :rightContent="rightContent"></view-box>
</template>

<script>
import {
  reactive, ref, onUnmounted, watch, computed,
} from 'vue';
import ViewBox from './ViewBox.vue';

const SerialPort = window.require('serialport');

const Bauds = [300, 1200, 2400, 9600, 19200, 38400, 115200];
const getPortsSelectForm = () => {
  const selectRef = ref(null);
  const Ports = ref([]);

  const leftContent = ref('');
  const rightContent = ref('');

  let serialIns = null;
  const selectFormRules = reactive({
    comName: [
      { required: true, message: '请选择串口', trigger: 'blur' },
    ],
    baudRate: [
      { required: true, message: '请选择波特率', trigger: 'blur' },
    ],
  });
  const selectForm = reactive({
    comName: '',
    baudRate: '',
  });

  const msgRef = ref(null);
  const msgForm = reactive({
    msg: '',
  });
  const msgFormRules = reactive({
    msg: [
      { required: true, message: '请输入消息', trigger: 'blur' },
    ],
  });

  const getSerInstance = () => {
    console.log(parseInt(selectForm.baudRate, 10));
    serialIns = new SerialPort(selectForm.comName, {
      baudRate: parseInt(selectForm.baudRate, 10),
    }, (err) => { console.log(err); });
    console.log(serialIns);
    serialIns.on('data', (data) => {
      console.log(data);
      rightContent.value += data;
    });
    return serialIns;
  };
  const sendMes = () => {
    serialIns.write(msgForm.msg, (err) => {
      if (err) {
        return console.log('Error on write: ', err.message);
      }
      console.log('message written');
      return true;
    });
  };

  let timer;
  // 获取串口定时器
  const getPorts = () => {
    SerialPort.list().then((ports) => {
      Ports.value = ports;
      timer = setTimeout(getPorts, 2000);
    });
  };

  // 获取串口定时器启动
  getPorts();

  const msgBoxShow = computed(() => !!(selectForm.comName && selectForm.baudRate));
  watch(() => msgBoxShow.value, (val) => {
    console.log(val, serialIns);
    if (val && !serialIns) {
      getSerInstance();
    }
  }, { deep: true });

  onUnmounted(() => {
    clearTimeout(timer);
  });
  return {
    selectForm,
    Ports,
    selectRef,
    selectFormRules,
    msgBoxShow,
    leftContent,
    rightContent,
    serialIns,
    sendMes,
    msgForm,
    msgRef,
    msgFormRules,
  };
};

export default {
  name: 'Home',
  components: {
    ViewBox,
  },
  setup() {
    return {
      ...getPortsSelectForm(),
      Bauds,
    };
  },
  methods: {
    onSubmit() {
      this.selectRef.validate((valid) => {
        if (valid) {
          console.log(this.selectForm);
          return true;
        }
        return false;
      });
    },
    onSend() {
      this.msgRef.validate((valid) => {
        if (valid) {
          this.leftContent += this.msgForm.msg;
          this.sendMes();
          this.msgRef.resetFields();
          return true;
        }
        return false;
      });
    },
  },
};
</script>
